package com.example.sherlockzhong.plush_v2.Models;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.example.sherlockzhong.plush_v2.Constant;
import com.example.sherlockzhong.plush_v2.Constants.UrlConstant;
import com.example.sherlockzhong.plush_v2.Utils.NetworkUtils;

import org.json.JSONArray;
import org.json.JSONTokener;

/**
 * Created by SherlockZhong on 9/18/14.
 */
public class EcardModel {

    public static boolean verify(String password, Activity activity) {
        if (Constant.STUDENT_ID != null && Constant.STUDENT_TOKEN != null) {
            try {
                String result = null;
                Constant.failedJsonObject = NetworkUtils.httpGetVerbose(String.format(UrlConstant.ecardVerifyUrl, Constant.STUDENT_ID, Base64.encodeToString(password.getBytes(), Base64.NO_WRAP)));
                if (Constant.failedJsonObject.get("status").toString().equalsIgnoreCase("200") && Constant.failedJsonObject.get("msg").toString().equalsIgnoreCase("ok")) {
                    result = Constant.failedJsonObject.get("data").toString();
                }
                if (result != null) {
                    SharedPreferences sp = activity.getSharedPreferences("user", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("ecardVerified", true);
                    editor.commit();
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static JSONArray getData(String type) {
        if (Constant.STUDENT_ID != null && Constant.ECARD_VERIFIED) {
            try {
                String result = NetworkUtils.httpGet(String.format((type == "refresh") ? UrlConstant.ecardRefreshUrl : UrlConstant.ecardHistoryUrl, Constant.STUDENT_ID, Constant.STUDENT_TOKEN));
                if (result != null) {
                    JSONTokener jsonTokener = new JSONTokener(result);
                    JSONArray jsonArray = (JSONArray) jsonTokener.nextValue();
                    return jsonArray;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static boolean isVerify() {
        return Constant.STUDENT_ID != null && Constant.STUDENT_TOKEN != null && Constant.ECARD_VERIFIED;
    }

}
